package com.lam.schedule.common.config;

import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import com.lam.common.components.redis.RedisUtil;
import com.lam.common.utils.CollectionUtil;
import com.lam.common.utils.IpUtils;
import com.lam.schedule.common.constant.ScheduleConstant;
import com.lam.schedule.common.scheduler.factory.ScheduleManage;
import com.lam.schedule.common.scheduler.model.ScheduleProperties;
import com.lam.schedule.common.scheduler.model.TargetClass;
import com.lam.schedule.common.scheduler.util.TaskUtils;

/**
 * @author lam
 *
 */
@Component
@Order(2)
public class InitSchedule implements ApplicationListener<ContextRefreshedEvent> {
	
	protected final Logger logger = LoggerFactory.getLogger(getClass());
	
	private volatile AtomicBoolean isInited = new AtomicBoolean(false);
	
	@Autowired
	private ScheduleProperties scheduleProperties;

	@Override
	public void onApplicationEvent(ContextRefreshedEvent event) {
		
		//防止重复触发
        if(!isInited.compareAndSet(false, true)) {
            return;
        }
        //开启任务
        start(event);
	}
	
	private void start(ContextRefreshedEvent event) {
		
		//加载定时任务到定时器上面
		ScheduleManage scheduleManage = event.getApplicationContext().getBean(ScheduleManage.class);
		scheduleManage.init();
		
		//扫描所有加了 TaskTarget 注解的类和方法，并放入Redis
		List<TargetClass> list = TaskUtils.scanTargetClass(scheduleProperties.getTargetClassPackage());
		String key = ScheduleConstant.TARGET_CLASS_KEY + IpUtils.getHostIp();
		RedisUtil.del(key);
		if(CollectionUtil.isNotEmpty(list)) {
			RedisUtil.set(key, list);
		}
    }

}
